import axios from "axios";
import Router from "@/router";
import {showFailToast, showNotify, showToast} from "vant";

// 创建 Axios 实例
const request = axios.create({
    timeout: 10000
});

//携带Cookie
request.defaults.withCredentials = true;

request.interceptors.request.use(
    async config => {
        let type = null;
        if (navigator.userAgent.match(
            /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)) {
            type = 'mobile';
        }else {
            type = 'PC';
        }
        config.headers['Equipment-Type'] = type;
        return config;
    }
)


// 在响应接收之前拦截响应
request.interceptors.response.use(
    response => {
        if (response.data.code !== 2000) {
            showFailToast(response.data.msg ? response.data.msg : "服务器繁忙，请稍后再试")
        }
        return response;
    },
    error => {
        //阿赖添加
        // console.log("阿赖")
        if(error.message.includes('timeout')) {   // 判断请求异常信息中是否含有超时timeout字符串
            showFailToast("请求超时，请检查你的网络")
            return Promise.resolve({
                data: {
                    code: 5001,
                    showMessage: false
                }
            });
        }
        //结束
        if (error.response && error.response.status === 401) {
            // 处理服务器返回的 401 异常
            // 这里可以执行一些操作，比如重定向到登录页面或显示未授权的错误提示
            //console.log(error);
            showNotify({ type: 'danger', message: error.response.data });
            Router.push("/login").then();
            return Promise.resolve({
                data: {
                    code: 5001,
                    showMessage: false
                }
            })
        } else {
            console.log(error)
        }
        showFailToast("网络连接失败，请检查你的网络")
        console.log(error)
        return Promise.resolve({
            data: {
                code: 5001,
                showMessage: false
            }
        })
    }
)

export default request
